package com.dongdongqiang.common.base;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 登录网页拦截器
 * Created by zzb on 16/4/8.
 */
public abstract class AbstractWebInterceptor extends AuthController implements HandlerInterceptor {
    abstract public String [] getUrlPattern();
    abstract public String  getRedirectUrl();
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //拦截正则
        String url = httpServletRequest.getRequestURL().toString();
        boolean match = false;
        for (String s : getUrlPattern()) {
            Pattern pattern = Pattern.compile(s);
            Matcher matcher = pattern.matcher(url);
            while (matcher.find()) {
                match = true;
                break;
            }
            if (match) break;
        }
        if (match) {
            Object user = getCurrentUser(httpServletRequest);
            if (user == null) {
                httpServletResponse.sendRedirect(getRedirectUrl());
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
